package com.smartcruise.main.contactsFragment;

import android.text.TextUtils;

import com.smartcruise.R;
import com.smartcruise.data.Contacts;
import com.smartcruise.util.sortLetter.CharacterParser;
import com.smartcruise.util.sortLetter.SortModel;

import java.util.ArrayList;
import java.util.List;

import io.realm.RealmResults;

/**
 * Created by FengChaoQun
 * on 2018/3/6 0006
 */

public class SearchContactPresenterImp implements SearchContactsContract.Presenter {

    private SearchContactsContract.View mView;
    private CharacterParser characterParser = new CharacterParser();

    public SearchContactPresenterImp(SearchContactsContract.View mView) {
        this.mView = mView;
    }

    @Override
    public void start() {

    }

    @Override
    public void search(String searchKey) {
        if (TextUtils.isEmpty(searchKey)) {
            mView.showToast(mView.getActivity().getString(R.string.searchContentNotAllowEmpty));
            return;
        }

        RealmResults<Contacts> all = mView.getRealm().where(Contacts.class)
                .contains("userName", searchKey).findAll();

        List<SortModel<Contacts>> sortModels = new ArrayList<>();
        for (Contacts contact : all) {
            SortModel<Contacts> sortModel = new SortModel<>();
            sortModel.setData(contact);
            if (contact.isEmergency()) {
                sortModel.setRemark(1);
            }

            //汉字转换成拼音
            String pinyin = characterParser.getSelling(contact.getUserName());
            String sortString = pinyin.substring(0, 1).toUpperCase();
            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }
            sortModels.add(sortModel);
        }
        if (sortModels.isEmpty()) {
            mView.showToast("没有找到");
        } else {
            mView.showResult(sortModels);
        }
    }
}
